import React, { useEffect, useState } from "react";
import "@/assets/css/main.scss";
import ModelPopup from "@/components/ModelPopup";
import setImg from "@/assets/images/setImg.png";
import waringImg from "@/assets/images/waringImg.png";
import arrowImg from "@/assets/images/arrowImg.png";
import newImg from "@/assets/images/newImg.png";
import endImg from "@/assets/images/endImg.png";
import cardImg from "@/assets/images/cardImg.png";
import oneImg from "@/assets/images/oneImg.png";
import twoImg from "@/assets/images/twoImg.png";
import threeImg from "@/assets/images/threeImg.png";
import closeImg from "@/assets/images/closeImg.png";
import welcomeImg from "@/assets/images/welcomeImg.png";
import caleImg from "@/assets/images/caleImg.png";
import timeImg from "@/assets/images/timeImg.png";
import stepImg from "@/assets/images/stepImg.png";
import timeTipImg from "@/assets/images/timeTipImg.png";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
    getHomeData,
    getDailySportData,
    getAbnormalLast,
    getSportClock,
    login
} from "@/utils/dataUtil";
import {
    getUserLogin,
    getUserHome,
    setUserHome,
    getUserSport,
    setUserSport,
    getUserAbnormal,
    setUserAbnormal,
    getUserWelcome,
    setUserWelcome,
} from "@/utils/storageUtil";
import {
    timeConversion,
    timeDiff,
    getCurrentDate,
} from "@/utils/dateUtil";
import { PullToRefresh, Image, Toast, Popup } from "antd-mobile";

//过高心率  high_heart_rate 2022-01-13， 16:00:10-16:11:30 有过⾼⼼率，包含 xx 条异常记录，最高xx 次/分钟  ==
//过低心率  low_heart_rate 2022-01-13， 16:00:10-16:11:30 有过低⼼率，包含两条异常记录，最低xx 次/分钟  ==
//异常心博  abnormal_heart_beat 2021-04-13，16:00:10-16:01:30 有异常⼼搏
//过低血氧 low_spo2  2022-01-13， 16:00:10-16:11:30 有过低血氧，包含两条异常记录，最低 xx %    ==
//睡眠异常：2021-04-13，睡眠总时长为 xx 小时，睡眠时间过短
//压力异常：stress 2021-04-13， 15:50，压⼒值为 xx，处于轻度/中度/重度 压力状态。

export default function NormalMain(props) {
    const navigate = useNavigate();

    const [searchParams, setSearchParams] = useSearchParams();

    //是否显示欢迎
    const [visibleMadel, setVisibleMadel] = useState(false);
    //运动中高心率提示
    const [visibleSportTip, setVisibleSportTip] = useState(false);
    //打卡的提示
    const [visibleClockTip, setVisibleClockTip] = useState(false);
    //用户数据
    const [homeData, setHomeData] = useState({
        info: {},
        activities: [],
        message: {},
    });

    const [dailyData, setDailyData] = useState({
        clock: true,
        config: { kcal: 0, steps: 0, intensity: 0, notify: 0 },
        intensityRanks: [],
        kcalRanks: [],
        stepsRanks: [],
    });

    const [selfkcalRanks, setSelfkcalRanks] = useState([]);
    const [selfStepsRanks, setSelfStepsRanks] = useState([]);
    const [selfIntensityRanks, setSelfIntensityRanks] = useState([]);

    //异常数据
    const [abLast, setAbLast] = useState("");

    //点击关闭弹出层
    const clickCloseMadel = () => {
        setVisibleMadel(false);
    };

    //点击跳转到更多活动消息页面
    const clickMoreMsg = () => {
        navigate("/msg");
    };

    //点击跳转到设置页面按钮
    const clickSettingBtn = () => {
        navigate("/set", { state: { name: homeData.info.companyName } });
    };

    //点击跳转到更多活动按钮
    const clickMoreActivityBtn = () => {
        navigate("/activity");
    };

    //点击排行榜更多按钮
    const clickRankMoreBtn = (tab) => {
        navigate(`/rank`, { state: { tab: tab, id: props.employeeId } });
    };

    const getHomeMethod = async (rf = false) => {
        const miId = searchParams.get("mi_id");
        
        if(rf) {
            let response = await login({ miId: miId });
            if (response.status === 5000) {
                props.refresh();
                return;
            }
        }

        getHomeData().then((res) => {
            if (res.status === 1) {
                setHomeData(res.data);
                //存储
                setUserHome(res.data);
                //弹出欢迎提示框
                if (getUserWelcome(miId) === null) {
                    setVisibleMadel(true);
                    setUserWelcome(miId);
                }
            }
        });

        getDailySportData().then((res) => {
            setSelfkcalRanks(
                res.data.kcalRanks.filter(
                    (item) => item.employeeId === props.employeeId
                )
            );
            setSelfStepsRanks(
                res.data.stepsRanks.filter(
                    (item) => item.employeeId === props.employeeId
                )
            );
            setSelfIntensityRanks(
                res.data.intensityRanks.filter(
                    (item) => item.employeeId === props.employeeId
                )
            );
            setDailyData(res.data);
            //存储
            setUserSport(res.data);
        });

        getAbnormalLast().then((res) => {
            if (res.data === null || res.data === "null") {
                res.data = "";
            }
            setAbLast(res.data);
            //存储
            setUserAbnormal(res.data);
        });
    };

    useEffect(() => {
        const currentUserAbnormal = getUserAbnormal();
        const currentUserHome = getUserHome();
        const currentUserLogin = getUserLogin();
        const currentUserSport = getUserSport();
        if (
            currentUserHome !== null &&
            currentUserLogin !== null &&
            currentUserSport !== null
        ) {
            setHomeData(currentUserHome);
            setSelfkcalRanks(
                currentUserSport.kcalRanks.filter(
                    (item) => item.employeeId === currentUserLogin.employeeId
                )
            );
            setSelfStepsRanks(
                currentUserSport.stepsRanks.filter(
                    (item) => item.employeeId === currentUserLogin.employeeId
                )
            );
            setSelfIntensityRanks(
                currentUserSport.intensityRanks.filter(
                    (item) => item.employeeId === currentUserLogin.employeeId
                )
            );
            setDailyData(currentUserSport);
            setAbLast(currentUserAbnormal);
            return;
        }
        getHomeMethod();
    }, [props.employeeId]);

    //点击跳转到活动页面
    const clickActivityItem = (id) => {
        navigate("/detail", { state: { id: id } });
    };

    //点击一键打卡按钮
    const clickOneTouchBtn = () => {
        if (dailyData.clock === true) {
            Toast.show({
                content: "你已完成一键打卡",
                maskClickable: false,
            });
            return;
        }
        getSportClock().then((res) => {
            if (res.status === 1) {
                Toast.show({
                    content: "一键打卡成功",
                    maskClickable: false,
                });
                let current = JSON.parse(JSON.stringify(dailyData));
                current.clock = true;
                setDailyData(current);
            }
        });
    };

    return (
        <>
            <div className="mainContainer">
                {/* 开始内容的开发 */}
                <PullToRefresh onRefresh={() => getHomeMethod(true)}>
                    <div className="mainSmall">
                        <div className="mainHead">
                            {/* 用户基本信息 */}
                            <div className="mainUserInfo">
                                <div className="mainInfoLeft">
                                    {homeData.info.logo && (
                                        <img
                                            className="mainAvatar"
                                            src={homeData.info.logo}
                                            alt=""
                                        />
                                    )}

                                    <div className="mainInfoBox">
                                        <div className="mainInfoName">
                                            {homeData.info.name !== undefined &&
                                                homeData.info.name !== null &&
                                                homeData.info.name}
                                        </div>
                                        <div className="mainInfoCom">
                                            {homeData.info.companyName !== undefined &&
                                                homeData.info.companyName !== null &&
                                                homeData.info.companyName}
                                        </div>
                                    </div>
                                </div>
                                <div className="mainInfoRight" onClick={clickSettingBtn}>
                                    <img src={setImg} alt="" />
                                </div>
                            </div>

                            {/* 异常 */}
                            {abLast !== null && abLast !== "" && (
                                <div className="mainUserError">
                                    <img className="mainError" src={waringImg} alt="" />
                                    {abLast}
                                </div>
                            )}

                            {homeData.message.msg && homeData.message.msg.length !== 0 && (
                                <div className="mainMsgBox">
                                    {/* 头部标题 */}
                                    <div className="mainMsgHead">
                                        <div className="mainMsgTit">最近消息</div>
                                        <div className="mainMsgMore" onClick={clickMoreMsg}>
                                            <div className="mainMsgCount">
                                                {homeData.message.count && homeData.message.count}
                                                条新消息
                                            </div>
                                            <img className="mianMsgArrow" src={arrowImg} alt="" />
                                        </div>
                                    </div>

                                    {/* 消息模块 */}
                                    <div className="mainMsgMinBox">
                                        {homeData.message.msg &&
                                            homeData.message.msg.map((value, index) => (
                                                <div
                                                    className="mainMsgMin"
                                                    style={{ marginTop: index === 1 ? "0.5rem" : 0 }}
                                                    key={index}
                                                    onClick={() => clickActivityItem(value.id)}
                                                >
                                                    <div className="mainMsgMinIcon">
                                                        <img
                                                            className="mainMsgMinIcons"
                                                            src={value.expire === 1 ? newImg : endImg}
                                                            alt=""
                                                        />
                                                        <div className="mainActivity">
                                                            <div className="mainActivityTit">
                                                                {value.expire === 1
                                                                    ? "活动上新"
                                                                    : "活动即将结束"}
                                                            </div>
                                                            <div className="mainActivityTxt">
                                                                {value.activityName}
                                                                {value.expire === 1
                                                                    ? "活动上新了"
                                                                    : timeDiff(getCurrentDate(), value.endDate) <=
                                                                        0
                                                                        ? "活动今天就结束了"
                                                                        : `活动还有${timeDiff(
                                                                            getCurrentDate(),
                                                                            value.endDate
                                                                        )}天就结束了`}
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="mainMsgDate">
                                                        {timeConversion(value.createTime)}
                                                    </div>
                                                </div>
                                            ))}
                                    </div>
                                </div>
                            )}
                            {/* 消息 */}
                        </div>

                        {/* 内容部分 */}
                        <div className="mainContent">
                            {/* 日常运动 */}
                            <div className="mainSportBox">
                                {/* 头部标题 */}
                                <div className="mainSportHead">
                                    <div className="mainSportHeadTit">日常运动</div>
                                    {
                                        dailyData.clock === false && (<div className="mainClockBox">
                                            <div className="mainClockTxt" onClick={() => setVisibleClockTip(true)}>
                                                <img className="mainClockIcon" src={timeTipImg} alt="" />
                                                <span>今日未打卡</span>
                                            </div>
                                            <div className="mainSportHeadCard" onClick={clickOneTouchBtn}>
                                                <img className="mainSportHeadIcon" src={cardImg} alt="" />
                                                <p className="mainHeadCardTxt">一键打卡</p>
                                            </div>
                                        </div>)
                                    }
                                </div>

                                {/* 卡路里排行 */}
                                <div className="mainRankBox">
                                    <div className="mainCaleBox">
                                        <div className="mainCaleBoxTit">
                                            <img className="mainCaleBoxTitImg" src={caleImg} alt="" />
                                        </div>

                                        {/* 自己的排名 */}
                                        {selfkcalRanks.map((item, index) => (
                                            <div className="mainSelfRank" key={index}>
                                                <div className="mainSelfRankLeft">
                                                    {item.rank <= 3 && (
                                                        <img
                                                            className="mainSelfRankIcon"
                                                            src={
                                                                item.rank === 1
                                                                    ? oneImg
                                                                    : item.rank === 2
                                                                        ? twoImg
                                                                        : threeImg
                                                            }
                                                            alt=""
                                                        />
                                                    )}
                                                    {item.rank > 3 && (
                                                        <p className="mainSelfRankTxt">{item.rank}</p>
                                                    )}

                                                    <p className="mainSelfRankName">我自己</p>
                                                </div>
                                                <div className="mainSelfRankRight">
                                                    <span className="mainSelfRankCount">{item.kcal}</span>
                                                    <span className="mainSelfRankUnit">kcal</span>
                                                </div>
                                            </div>
                                        ))}

                                        {/* 其他排名 */}
                                        {dailyData.kcalRanks.map(
                                            (item, index) =>
                                                index < 3 && (
                                                    <div className="mainOtherRank" key={index}>
                                                        <div className="mainOtherRankUl">
                                                            <div className="mainSelfRankLeft">
                                                                {index === 0 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={oneImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 1 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={twoImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 2 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={threeImg}
                                                                        alt=""
                                                                    />
                                                                )}

                                                                <p className="mainSelfRankName">
                                                                    {item.employeeName}
                                                                </p>
                                                            </div>
                                                            <div className="mainSelfRankRight">
                                                                <span className="mainSelfRankCount">
                                                                    {item.kcal}
                                                                </span>
                                                                <span className="mainSelfRankUnit">kcal</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                )
                                        )}

                                        {/* 更多 */}
                                        <div
                                            className="mainOtherRankMore"
                                            onClick={() => clickRankMoreBtn(1)}
                                        >
                                            更多
                                        </div>
                                    </div>

                                    <div className="mainCaleBox mainStepBox">
                                        <div className="mainCaleBoxTit">
                                            <img
                                                className="mainCaleBoxTitImgOne"
                                                src={stepImg}
                                                alt=""
                                            />
                                        </div>

                                        {/* 自己的排名 */}
                                        {selfStepsRanks.map((item, index) => (
                                            <div className="mainSelfRank" key={index}>
                                                <div className="mainSelfRankLeft">
                                                    {item.rank <= 3 && (
                                                        <img
                                                            className="mainSelfRankIcon"
                                                            src={
                                                                item.rank === 1
                                                                    ? oneImg
                                                                    : item.rank === 2
                                                                        ? twoImg
                                                                        : threeImg
                                                            }
                                                            alt=""
                                                        />
                                                    )}
                                                    {item.rank > 3 && (
                                                        <p className="mainSelfRankTxt">{item.rank}</p>
                                                    )}
                                                    <p className="mainSelfRankName">我自己</p>
                                                </div>
                                                <div className="mainSelfRankRight">
                                                    <span className="mainSelfRankCount">
                                                        {item.steps}
                                                    </span>
                                                    <span className="mainSelfRankUnit">步</span>
                                                </div>
                                            </div>
                                        ))}

                                        {/* 其他排名 */}
                                        {dailyData.stepsRanks.map(
                                            (item, index) =>
                                                index < 3 && (
                                                    <div className="mainOtherRank" key={index}>
                                                        <div className="mainOtherRankUl">
                                                            <div className="mainSelfRankLeft">
                                                                {index === 0 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={oneImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 1 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={twoImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 2 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={threeImg}
                                                                        alt=""
                                                                    />
                                                                )}

                                                                <p className="mainSelfRankName">
                                                                    {item.employeeName}
                                                                </p>
                                                            </div>
                                                            <div className="mainSelfRankRight">
                                                                <span className="mainSelfRankCount">
                                                                    {item.steps}
                                                                </span>
                                                                <span className="mainSelfRankUnit">步</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                )
                                        )}

                                        {/* 更多 */}
                                        <div
                                            className="mainOtherRankMore"
                                            onClick={() => clickRankMoreBtn(2)}
                                        >
                                            更多
                                        </div>
                                    </div>
                                    <div className="mainCaleBox mainTimeBox">
                                        <div className="mainCaleBoxTit">
                                            <img
                                                className="mainCaleBoxTitImgOne"
                                                src={timeImg}
                                                alt=""
                                            />
                                            <img
                                                onClick={() => setVisibleSportTip(true)}
                                                className="mainCaleTipImg"
                                                src={timeTipImg}
                                                alt=""
                                            />
                                        </div>

                                        {selfIntensityRanks.map((item, index) => (
                                            <div className="mainSelfRank" key={index}>
                                                <div className="mainSelfRankLeft">
                                                    {item.rank <= 3 && (
                                                        <img
                                                            className="mainSelfRankIcon"
                                                            src={
                                                                item.rank === 1
                                                                    ? oneImg
                                                                    : item.rank === 2
                                                                        ? twoImg
                                                                        : threeImg
                                                            }
                                                            alt=""
                                                        />
                                                    )}
                                                    {item.rank > 3 && (
                                                        <p className="mainSelfRankTxt">{item.rank}</p>
                                                    )}
                                                    <p className="mainSelfRankName">我自己</p>
                                                </div>
                                                <div className="mainSelfRankRight">
                                                    <span className="mainSelfRankCount">
                                                        {item.intensity}
                                                    </span>
                                                    <span className="mainSelfRankUnit">分钟</span>
                                                </div>
                                            </div>
                                        ))}
                                        {/* 自己的排名 */}

                                        {/* 其他排名 */}
                                        {dailyData.intensityRanks.map(
                                            (item, index) =>
                                                index < 3 && (
                                                    <div className="mainOtherRank" key={index}>
                                                        <div className="mainOtherRankUl">
                                                            <div className="mainSelfRankLeft">
                                                                {index === 0 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={oneImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 1 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={twoImg}
                                                                        alt=""
                                                                    />
                                                                )}
                                                                {index === 2 && (
                                                                    <img
                                                                        className="mainSelfRankIcon"
                                                                        src={threeImg}
                                                                        alt=""
                                                                    />
                                                                )}

                                                                <p className="mainSelfRankName">
                                                                    {item.employeeName}
                                                                </p>
                                                            </div>
                                                            <div className="mainSelfRankRight">
                                                                <span className="mainSelfRankCount">
                                                                    {item.intensity}
                                                                </span>
                                                                <span className="mainSelfRankUnit">分钟</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                )
                                        )}

                                        {/* 更多 */}
                                        <div
                                            className="mainOtherRankMore"
                                            onClick={() => clickRankMoreBtn(3)}
                                        >
                                            更多
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* 活动 */}
                            {homeData.activities.length !== 0 && (
                                <div className="mainActivityBox">
                                    {/* 头部标题 */}
                                    <div className="mainMsgHead">
                                        <div className="mainMsgTit">活动</div>
                                        <div className="mainMsgMore" onClick={clickMoreActivityBtn}>
                                            <img className="mianMsgArrow" src={arrowImg} alt="" />
                                        </div>
                                    </div>

                                    {/* 活动的ul */}
                                    <div className="mainActivityUl">
                                        {homeData.activities.map((item, index) => (
                                            <div
                                                className="mainActivityLi"
                                                key={index}
                                                onClick={() => clickActivityItem(item.id)}
                                            >
                                                <Image
                                                    src={item.cover}
                                                    lazy
                                                    width={"2.4rem"}
                                                    height={"1.39rem"}
                                                    style={{
                                                        borderRadius: "0.16rem",
                                                        marginRight: "0.25rem",
                                                    }}
                                                    fit="cover"
                                                />
                                                <div className="mainActivityInfo">
                                                    <div className="mainActivityInfoTit">{item.name}</div>
                                                    <div className="mainActivityInfoBtn">
                                                        {item.status !== "un_enroll" ? "去完成" : "去报名"}
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </PullToRefresh>

                {/* 欢迎来到公司弹出层 */}
                <ModelPopup visibleMadel={visibleMadel}>
                    <div className="mpContentBox">
                        <div className="mpContentBoxImg">
                            <img className="welcomeImg" src={welcomeImg} alt="" />
                            <p className="welcomeTxt">欢迎你</p>
                            <p className="welcomeName">
                                加入{homeData.info.companyName && homeData.info.companyName}
                            </p>
                        </div>
                        {/* 关闭按钮 */}
                        <div className="moCloseBox">
                            <img
                                className="moCloseIMg"
                                src={closeImg}
                                alt=""
                                onClick={clickCloseMadel}
                            />
                        </div>
                    </div>
                </ModelPopup>

                {/* 中高心率的提示 */}
                <Popup
                    visible={visibleSportTip}
                    onMaskClick={() => {
                        setVisibleSportTip(false);
                    }}
                    bodyStyle={{
                        borderTopLeftRadius: "23px",
                        borderTopRightRadius: "23px",
                        height: "4.1rem",
                    }}
                >
                    <div className="mainSportTip">
                        运动时当心率达到最大心率的65%或步频达到100次/分时，将被记录为中高强度活动时长
                    </div>

                    <div
                        className="mainSportBtnBox"
                        onClick={() => {
                            setVisibleSportTip(false);
                        }}
                    >
                        <div className="mainSportBtn">确定</div>
                    </div>
                </Popup>

                {/* 打卡的提示 */}
                <Popup
                    visible={visibleClockTip}
                    onMaskClick={() => {
                        setVisibleClockTip(false);
                    }}
                    bodyStyle={{
                        borderTopLeftRadius: "23px",
                        borderTopRightRadius: "23px",
                        height: "4.1rem",
                    }}
                >
                    <div className="mainSportTip">
                        打卡后将会统计和展示今日日常运动中的卡路里、步数和中高强度活动的时长数据
                    </div>

                    <div
                        className="mainSportBtnBox"
                        onClick={() => {
                            setVisibleClockTip(false);
                        }}
                    >
                        <div className="mainSportBtn">确定</div>
                    </div>
                </Popup>

            </div>
        </>
    );
}
